<?php
/**
 * @Copyright (C) 2014 
 * @Author  kevin <xuwenhu369@163.com>
 * @Version  Beta 1.0
 */

namespace common\component;
use Yii;


/**
 * 公共静态函数库
 */
class AdCommon
{

	/**
	 * 生成唯一字符串
	 * @return string
	 */
	public static function uniqueGuid()
	{
		$charid = strtoupper(md5(uniqid(mt_rand(), true)));
		$uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid, 12, 4).substr($charid, 16, 4).substr($charid, 20, 12);
		return $uuid;
	}

	/**
	 *  非四舍五入取取小数点
	 * @param type $number
	 * @return type
	 */
	public static function floor_money_format($number, $num = 2)
	{
		$number = floor($number*100)/100;
		return number_format($number, $num, '.', '');
	}

	/**
	 *  格式化金额
	 * @param type $number
	 * @param type $type
	 * @return type
	 */
	public static function formatMoney($number, $type = 4)
	{
		return number_format($number, $type, ".", "");
	}

	/**
	 *  返回错误信息
	 * @param type $array
	 * @return type
	 */
	public static function modelMessage($array)
	{
		if(count($array)<=0)
		{
			return;
		}
		$msg = '';
		foreach($array as $val)
		{
			$msg .= isset($val[0]) ? $val[0] : $val;
		}
		return $msg;
	}

	/**
	 * 检查输入的是否为数字
	 * @access public
	 * @param  $val 
	 * @return bool true false
	 */
	public static function isNumber($val)
	{
		if(preg_match("/^[0-9]+$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 *  获取时间错
	 */
	public static function get_microtime()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float) $usec+(float) $sec);
	}

	/**
	 * 检查输入的是否为手机号
	 * @access public
	 * @param  $val 
	 * @return bool true false
	 */
	public static function isMobile($val)
	{

		//该表达式可以验证那些不小心把连接符“-”写出“－”的或者下划线“_”的等等
		if(preg_match("/^13[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查输入的是否为邮编
	 * @access public
	 * @param  $val 
	 * @return bool true false
	 */
	public static function isPostcode($val)
	{
		if(preg_match("/^[0-9]{4,6}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 邮箱地址合法性检查
	 * @access public
	 * @param  $val 
	 * @param  $domain
	 * @return bool true false
	 */
	public static function isEmail($val, $domain = "")
	{
		if(!$domain)
		{
			if(preg_match("/^[a-z0-9-_.]+@[\da-z][\.\w-]+\.[a-z]{2,4}$/i", $val))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			if(preg_match("/^[a-z0-9-_.]+@".$domain."$/i", $val))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

	/**
	 * 验证身份证号
	 * @param $vStr
	 * @return bool
	 */
	public static function isCreditNo($vStr)
	{
		$vCity = array(
				'11', '12', '13', '14', '15', '21', '22',
				'23', '31', '32', '33', '34', '35', '36',
				'37', '41', '42', '43', '44', '45', '46',
				'50', '51', '52', '53', '54', '61', '62',
				'63', '64', '65', '71', '81', '82', '91'
		);

		if(!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr))
		{
			return false;
		}

		if(!in_array(substr($vStr, 0, 2), $vCity))
		{
			return false;
		}

		$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
		$vLength = strlen($vStr);

		if($vLength==18)
		{
			$vBirthday = substr($vStr, 6, 4).'-'.substr($vStr, 10, 2).'-'.substr($vStr, 12, 2);
		}
		else
		{
			$vBirthday = '19'.substr($vStr, 6, 2).'-'.substr($vStr, 8, 2).'-'.substr($vStr, 10, 2);
		}

		if(date('Y-m-d', strtotime($vBirthday))!=$vBirthday)
		{
			return false;
		}
		if($vLength==18)
		{
			$vSum = 0;

			for($i = 17; $i>=0; $i--)
			{
					  $vSubStr = substr($vStr, 17-$i, 1);
					  $vSum += (pow(2, $i)%11)*(($vSubStr=='a') ? 10 : intval($vSubStr, 11));
			}

			if($vSum%11!=1)
			{
				return false;
			}
		}

		return true;
	}

	/**
	 * 姓名昵称合法性检查，只能输入中文英文
	 * @access public
	 * @param  $val 被检查内容
	 * @return bool true false
	 */
	public static function isName($val)
	{
		if(preg_match("/^[\x80-\xffa-zA-Z0-9]{3,60}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查字符串长度是否符合要求(仅限于数字)
	 * @access public
	 * @param  int $val 
	 * @param  int $min 最小长度
	 * @param  int $max 最大长度
	 * @return bool true false
	 */
	public static function isNumLength($val, $min, $max)
	{
		$theelement = trim($val);
		if(preg_match("/^[0-9]{".$min.",".$max."}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查字符串长度是否符合要求(仅限于阿拉伯字母)
	 * @access public
	 * @param  string $val 
	 * @param  int $min 最小长度
	 * @param  int $max 最大长度
	 * @return bool true false
	 */
	public static function isEngLength($val, $min, $max)
	{
		$theelement = trim($val);
		if(preg_match("/^[a-zA-Z]{".$min.",".$max."}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查输入是否为英文
	 * @access public
	 * @param  string $theelement 
	 * @return bool true false
	 */
	public static function isEnglish($theelement)
	{
		if(preg_match("[\x80-\xff].", $theelement))
		{
			return false;
		}
		return true;
	}

	/**
	 * 检查是否输入为汉字
	 * @access public
	 * @param  string $sInBuf 
	 * @return bool true false
	 */
	public static function isChinese($val)
	{
		if(preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查输入值是否为合法人民币格式
	 * @access public
	 * @param  float $val  
	 * @return bool true false
	 */
	public static function isMoney($val)
	{
		if(preg_match("/^(-?\d+)(\.\d+)?/", $val))
		{
			return true;
		}
		if(preg_match("/^[0-9]{1,}\.[0-9]{1,4}$/", $val))
		{
			return true;
		}
		return false;
	}

	/**
	 * 检查输入IP是否符合要求
	 * @access public
	 * @param  string $val  
	 * @return bool true false
	 */
	public static function isIp($val)
	{
		return(bool) ip2long($val);
	}

	/**
	 * 如果元素值中包含除字母和数字以外的其他字符，则返回FALSE
	 * @access public
	 * @param  string $str 被验证内容
	 * @return bool
	 * @author Alisa
	 */
	public static function isAlpha_numeric($str)
	{
		return (!preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
	}

	/**
	 * 如果元素值中包含除字母/数字/下划线/破折号以外的其他字符，则返回FALSE
	 * @access public
	 * @param  string $str
	 * @return bool true false
	 */
	public static function alpha_dash($str)
	{
		return (!preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
	}

	/**
	 * 汇率兑换
	 * @access public
	 * @param  int $type 1人民币兑换美元 2美元兑换人民币
	 * @param  float $money 金额
	 * @param  float $rate汇率
	 * @return float
	 */
	public static function changeRates($type = 1, $money, $rate)
	{
		if($rate==0)
		{
			return $money;
		}

		if($type==1)
		{
			return self::format_money($money/$rate, 4);
		}
		else if($type==2)
		{
			return self::format_money($money*$rate, 4);
		}
		else
		{
			return 0;
		}
	}

	/**
	 *  非四舍五入取取小数点
	 * @param type $number
	 * @return type
	 */
	public static function format_money($number, $num = 2)
	{
		$number = floor($number*100)/100;
		return number_format($number, $num, '.', '');
	}
	
	/**
	 * 格式化日期
	 * @return type
	 */
	public static function format_weekday($time = 0)
	{
		$nowWeek = date('w', $time);
		$startDay = strtotime("-".($nowWeek == 0 ? 7 : $nowWeek)." days", $time);
		$weekDate = array(1 => '星期一', 2 => '星期二', 3 => '星期三', 4 => '星期四', 5 => '星期五', 6 => '星期六', 0 => '星期日');
		for ($i=1; $i<=7; $i++)
		{
			$dateDay = strtotime("+{$i} days", $startDay);
			$weekDay[] = array(date('Y-m-d', $dateDay), date('m.d', $dateDay), $weekDate[date('w', $dateDay)]);
		}
		return $weekDay;
	}

	/**
	 * @desc 截取字符串
	 * Enter description here ...
	 * @param string  $string 截取字符
	 * @param int     $start  开始位置
	 * @param int     $length  截取长度
	 * @param bool    $mode
	 * @param string  $dot
	 * @param string  $encode 编码格式
	 * @return string $strcut
	 */ 
	public static function substr($string,$start=0,$length,$mode=false,$dot='',$encode='utf-8')
	{
		$strlen = strlen($string);
    	if($strlen <= $length)
    	{
    		return $string;
    	}
    	$string = str_replace(array('&nbsp;','&amp;','&quot;','&lt;','&gt;','&#039;'), array(' ','&','"','<','>',"'"), $string);
    	$strcut = '';
    	if($encode == 'utf-8')
    	{
    		$n = $tn = $noc = 0;
    		while($n < $strlen)
    		{
    			$t = ord($string[$n]);
			    if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) 
			    {
				   $tn = 1; $n++; $noc++;
			    } 
			    elseif(194 <= $t && $t <= 223) 
			    {
				   $tn = 2; $n += 2; $noc += 2;
			    } 
			    elseif(224 <= $t && $t < 239) 
			    {
				   $tn = 3; $n += 3; $noc += 2;
			    } 
			    elseif(240 <= $t && $t <= 247) 
			    {
				   $tn = 4; $n += 4; $noc += 2;
			    } 
			    elseif(248 <= $t && $t <= 251) 
			    {
				   $tn = 5; $n += 5; $noc += 2;
			    } 
			    elseif($t == 252 || $t == 253) 
			    {
				   $tn = 6; $n += 6; $noc += 2;
			    } 
			    else 
			    {
				   $n++;
			    }
                if($noc >= $length) 
                {
				   break;
			    }
    			
    		}
    		if($noc > $length)
    		{
    			$n -= $tn;
    		}
    		$strcut = substr($string, 0, $n);
    	}
    	else 
    	{
    		for($i = 0; $i < $length; $i++)
    		{
    			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
    		}
    	}
    	$strcut = str_replace(array('&','"','<','>',"'"), array('&amp;','&quot;','&lt;','&gt;','&#039;'), $strcut);
    	return $strcut.$dot;
	}

	//获取 Model 错误信息中的 第一条，无错误时 返回 null
	public static function getModelError($model) {
		$errors = $model->getErrors();    //得到所有的错误信息
		if(!is_array($errors)) return '';
		$firstError = array_shift($errors);
		if(!is_array($firstError)) return '';
		return array_shift($firstError);
	}
	/**
	 * 提示信息
	 */
	public static function showMessage( $action = 'success', $content = '', $redirect = 'javascript:history.back(-1);', $timeout = 4 ) {
	
	    switch ( $action ) {
	        case 'success':
	            $titler = '操作完成';
	            $class = 'message_success';
	            $images = 'message_success.png';
	            break;
	        case 'error':
	            $titler = '操作未完成';
	            $class = 'message_error';
	            $images = 'message_error.png';
	            break;
	        case 'errorBack':
	            $titler = '操作未完成';
	            $class = 'message_error';
	            $images = 'message_error.png';
	            break;
	        case 'redirect':
	            header( "Location:$redirect" );
	            break;
	        case 'parentscript':
	            if ( empty( $redirect ) ) {
	                exit( '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body><script language="javascript">alert("' . $content . '");window.history.back(-1)</script></body></html>' );
	            } else {
	                exit( '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body><script language="javascript">alert("' . $content . '"); window.parent.location.href=" ' . $redirect . '   "</script></body></html>' );
	            }
	            break;
	        case 'script':
	            if ( empty( $redirect ) ) {
	                exit( '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body><script language="javascript">alert("' . $content . '");window.history.back(-1)</script></body></html>' );
	            } else {
	                exit( '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body><script language="javascript">alert("' . $content . '");window.location=" ' . $redirect . '   "</script></body></html>' );
	            }
	            break;
	
	    }
	
	    // 信息头部
	    $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>操作提示</title>
<style type="text/css">
body{font:12px/1.7 "\5b8b\4f53",Tahoma;}
html,body,div,p,a,h3{margin:0;padding:0;}
.tips_wrap{ background:#F7FBFE;border:1px solid #DEEDF6;width:780px;padding:50px;margin:50px auto 0;word-break:normal;word-wrap:break-word;}
.tips_inner{zoom:1;}
.tips_inner:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}
.tips_inner .tips_img{width:80px;float:left;}
.tips_info{float:left;line-height:35px;width:650px}
.tips_info h3{font-weight:bold;color:#1A90C1;font-size:16px;}
.tips_info p{font-size:14px;color:#999;}
.tips_info p.message_error{font-weight:bold;color:#F00;font-size:16px; line-height:22px}
.tips_info p.message_success{font-weight:bold;color:#1a90c1;font-size:16px; line-height:22px}
.tips_info p.return{font-size:12px}
.tips_info .time{color:#f00; font-size:14px; font-weight:bold}
.tips_info p a{color:#1A90C1;text-decoration:none;}
</style>
</head>
	
<body>';
	    // 信息底部
	    $footer = '</body></html>';
	
	    $body = '<script type="text/javascript">
        function delayURL(url) {
        var delay = document.getElementById("time").innerHTML;
        //alert(delay);
        if(delay > 0){
        delay--;
        document.getElementById("time").innerHTML = delay;
    } else {
    window.location.href = url;
    }
    setTimeout("delayURL(\'" + url + "\')", 1000);
    }
    </script><div class="tips_wrap">
    <div class="tips_inner">
        <div class="tips_img">
            <img src="' .'/static/images/' . $images . '"/>
        </div>
        <div class="tips_info">
	
            <p class="' . $class . '">' . $content . '</p>
            <p class="return">系统自动跳转在  <span class="time" id="time">' . $timeout . ' </span>  秒后，如果不想等待，<a href="' . $redirect . '">点击这里跳转</a></p>
        </div>
    </div>
</div><script type="text/javascript">
    delayURL("' . $redirect . '");
    </script>';
	
	    exit( $header . $body . $footer );
	}

}